<?php
	include "../common/db.inc";
	$pagesize = 12;
	$currentpage = 1;
	$numdisplay = 5;
	
	if (isset($_GET["page"]))
		$currentpage = $_GET["page"];	
	
	session_start();
	$userId = $_SESSION['user_id'];
	
	//xoa 
	if(isset($_GET['u']))
	{
		$mysqli = new mysqli($host, $username, $password,$dbname);
		$mysqli->set_charset('utf8');
		if (mysqli_connect_errno()) 
		{
		    printf("Connect failed: %s\n", mysqli_connect_error());
		    exit();
		}
		$userId = $mysqli->real_escape_string($_GET['u']);
		$ebookId = $mysqli->real_escape_string($_GET['e']);
		$query = ("call sp_DeleteNeededList('$userId', '$ebookId')");
		@$mysqli->query($query);
		$mysqli->close();
	}
	
	$mysqli = new mysqli($host, $username, $password,$dbname);
	$mysqli->set_charset('utf8');
	if (mysqli_connect_errno()) 
	{
	    printf("Connect failed: %s\n", mysqli_connect_error());
	    exit();
	}
	
	$start = ($currentpage-1) * $pagesize;
	$mysqli = new mysqli($host, $username, $password,$dbname);
	$mysqli->set_charset('utf8');
	$query = ("call sp_GetNeededListByUser('$userId', '$start', '$pagesize')");
	$CountEbook = 0;	
	if ($result = @$mysqli->query($query)) 
	{
		$i=0;
		$count =  mysqli_num_rows($result);
		echo "<div id='result'";
		echo "<table border='1' cellspacing='0'>";
	    while ($row = $result->fetch_row()) 
		{
			$ebookId = $row[0];
			$title = $row[1];
			$img = $image.$row[2];
			$mana = $row[4];
			$file_up = $row[5];
			if($i%4 == 0)
				echo "<tr>";
			echo "<td width='25%' valign='top'>";
			echo "<table><tr>";
			echo "<td valign='top'>";
			echo "<a href='XemChiTietSach.php?id=$ebookId'><img align='left' src='$img' width='60px' height='100px' alt='EBook'/></a>";
			echo "</td><td valign='top'>";
			echo "<a href='XemChiTietSach.php?id=$ebookId'>$title</a><br/>";
			echo "<label><i>Mana: </i>$mana</label><br/>";
			if($_SESSION['user_mana'] >= $mana)
				echo "<input type='button' value='Tải về' onClick='download(\"$userId\", \"$ebookId\",\"$file_up\")'></input>&nbsp;";
			else
					echo "<input type='button' disabled='disabled' value='Tải về'></input>";
			echo "<input type='button' value='Xóa' onClick='deleteNeededList(\"$userId\", \"$ebookId\")'></input>";
			echo "</td></tr></table>";
			echo "</td>";
			if($i % 4 == 3)
				echo "</tr>";
			else if($i == $count-1)
			{
				for($j=0;$j<4-($count%4);$j++)
					echo "<td>&nbsp;</td>";
				echo "</tr>";
			}
			$i++;
		}
		 $result->close();
		 echo "</table>";	
		
		include '../common/paging.php';
		$count = 0;
		$mysqli = new mysqli($host, $username, $password, $dbname);

		$query = "call sp_CountNeededListByUser('$userId')";
		$result = $mysqli->query($query);
		$row = $result->fetch_row();
		$count = $row[0];
		echo paging('showneededlist.php', $pagesize, $numdisplay, $count, $currentpage, '');
		
		$mysqli->close();
		echo "</div>";
	}	
?>
